package net.yienyien.process.bpel.util;

import java.util.Map;

import javax.wsdl.Message;
import javax.xml.namespace.QName;

import net.yienyien.process.bpel.BpelPackage;

import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EReference;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.xmi.XMLHelper;
import org.eclipse.emf.ecore.xmi.XMLResource;
import org.eclipse.emf.ecore.xmi.impl.SAXXMLHandler;
import org.eclipse.wst.wsdl.Definition;
import org.eclipse.wst.wsdl.WSDLPackage;

public class BpelHandler extends SAXXMLHandler {
	
	public BpelHandler(XMLResource xmiResource, XMLHelper helper,
			Map<?, ?> options) {
		super(xmiResource, helper, options);
	}


	@Override
	protected void setValueFromId(EObject object, EReference reference,
			String ids) {
		if(reference.equals(BpelPackage.eINSTANCE.getVariable_MessageTypeRef())) {
			setMessageFromQName(object, reference, ids);
		} else {
			super.setValueFromId(object, reference, ids);
		}
	}

	
	protected void setMessageFromQName(EObject object, EReference reference,
			String qname) {
		
		String[] parts=qname.split(":");
		if(parts.length!=2) {
			return;
		} 
		String ns=helper.getNamespaceURI(parts[0]);
		String localPart=parts[1];
		
		for(Resource resource:resourceSet.getResources()) {
			for(EObject o: resource.getContents()) {
				if(WSDLPackage.eINSTANCE.getDefinition().isInstance(o)) {
					Definition def=(Definition) o;
					if(def.getTargetNamespace().equals(ns)) {
						Message m=def.getMessage(new QName(ns, localPart));
						setFeatureValue(object, reference, m, -2);
						
					}
				}
			}
		}
	}
	
	
}
